<?php
#file: lunar_api.php
# 使用专业天文历法库实现精确的公历到农历转换

require_once 'vendor/autoload.php';

use Overtrue\ChineseCalendar\Calendar;
use DateTime;

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Allow-Headers: Content-Type');

// 只接受POST请求
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['error' => '只允许POST方法']);
    exit;
}

// 获取POST数据
$input = json_decode(file_get_contents('php://input'), true);

if (!isset($input['date'])) {
    http_response_code(400);
    echo json_encode(['error' => '缺少date参数']);
    exit;
}

try {
    // 验证并解析日期时间
    $datetime = DateTime::createFromFormat('Y-m-d H:i', $input['date']);
    if (!$datetime) {
        throw new Exception('日期格式错误，请使用"YYYY-MM-DD H:mm"格式');
    }

    $year = (int)$datetime->format('Y');
    $month = (int)$datetime->format('m');
    $day = (int)$datetime->format('d');
    $hour = (int)$datetime->format('H');

    // 使用专业天文历法库进行转换
    $calendar = new Calendar();
    $lunarInfo = $calendar->solar($year, $month, $day);

    // 计算时辰干支
    $gzHour = calculateHourGanZhi($year, $month, $day, $hour);

    // 构建返回结果
    $result = [
        'gregorian_date' => $datetime->format('Y-m-d H:i'),
        'lunar_date' => [
            'year' => $lunarInfo['lunar_year'],
            'month' => $lunarInfo['lunar_month'],
            'day' => $lunarInfo['lunar_day'],
            'is_leap_month' => $lunarInfo['leap_month'],
            'year_name' => $lunarInfo['ganzhi_year'] . '年',
            'month_name' => ($lunarInfo['leap_month'] ? '闰' : '') . $lunarInfo['lunar_month_chinese'],
            'day_name' => $lunarInfo['lunar_day_chinese']
        ],
        'gan_zhi' => [
            'year' => $lunarInfo['ganzhi_year'],
            'month' => $lunarInfo['ganzhi_month'],
            'day' => $lunarInfo['ganzhi_day'],
            'hour' => $gzHour
        ],
        'zodiac' => $lunarInfo['animal'],
        'cycle_year' => (($lunarInfo['lunar_year'] - 4) % 60) + 1,
        'hour_info' => [
            'hour_24' => $hour,
            'traditional_hour' => getTraditionalHourName($hour),
            'hour_ganzhi' => $gzHour
        ]
    ];

    echo json_encode($result, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);

} catch (Exception $e) {
    http_response_code(400);
    echo json_encode(['error' => $e->getMessage()]);
} catch (Error $e) {
    http_response_code(500);
    echo json_encode(['error' => '服务器内部错误: ' . $e->getMessage()]);
}

/**
 * 计算时辰干支
 * @param int $year
 * @param int $month
 * @param int $day
 * @param int $hour 24小时制
 * @return string 时辰干支
 */
function calculateHourGanZhi($year, $month, $day, $hour) {
    // 天干
    $heavenlyStems = ['甲', '乙', '丙', '丁', '戊', '己', '庚', '辛', '壬', '癸'];
    // 地支 (时辰)
    $earthlyBranches = ['子', '丑', '寅', '卯', '辰', '巳', '午', '未', '申', '酉', '戌', '亥'];

    // 确定时辰地支 (每个时辰2小时)
    $hourBranchIndex = intval($hour / 2);
    // 子时从23:00开始，需要特殊处理
    if ($hour == 23 || $hour == 0) {
        $hourBranchIndex = 0; // 子时
    } elseif ($hour == 1 || $hour == 2) {
        $hourBranchIndex = 1; // 丑时
    } elseif ($hour >= 3 && $hour <= 4) {
        $hourBranchIndex = 2; // 寅时
    } elseif ($hour >= 5 && $hour <= 6) {
        $hourBranchIndex = 3; // 卯时
    } elseif ($hour >= 7 && $hour <= 8) {
        $hourBranchIndex = 4; // 辰时
    } elseif ($hour >= 9 && $hour <= 10) {
        $hourBranchIndex = 5; // 巳时
    } elseif ($hour >= 11 && $hour <= 12) {
        $hourBranchIndex = 6; // 午时
    } elseif ($hour >= 13 && $hour <= 14) {
        $hourBranchIndex = 7; // 未时
    } elseif ($hour >= 15 && $hour <= 16) {
        $hourBranchIndex = 8; // 申时
    } elseif ($hour >= 17 && $hour <= 18) {
        $hourBranchIndex = 9; // 酉时
    } elseif ($hour >= 19 && $hour <= 20) {
        $hourBranchIndex = 10; // 戌时
    } elseif ($hour >= 21 && $hour <= 22) {
        $hourBranchIndex = 11; // 亥时
    }

    // 计算日干支索引以确定时辰天干
    $baseDate = new DateTime('1900-01-01');
    $currentDate = new DateTime(sprintf('%04d-%02d-%02d', $year, $month, $day));
    $daysDiff = $baseDate->diff($currentDate)->days;
    $dayStemIndex = (40 + $daysDiff) % 10;

    // 时辰天干计算规则 (根据日干确定时辰天干起始点)
    $hourStemStartMap = [
        0 => 0,  // 甲日 - 子时起甲
        1 => 2,  // 乙日 - 子时起丙
        2 => 4,  // 丙日 - 子时起戊
        3 => 6,  // 丁日 - 子时起庚
        4 => 8,  // 戊日 - 子时起壬
        5 => 0,  // 己日 - 子时起甲
        6 => 2,  // 庚日 - 子时起丙
        7 => 4,  // 辛日 - 子时起戊
        8 => 6,  // 壬日 - 子时起庚
        9 => 8   // 癸日 - 子时起壬
    ];

    $hourStemIndex = ($hourStemStartMap[$dayStemIndex] + $hourBranchIndex) % 10;

    return $heavenlyStems[$hourStemIndex] . $earthlyBranches[$hourBranchIndex];
}

/**
 * 获取传统时辰名称
 * @param int $hour 24小时制
 * @return string 传统时辰名称
 */
function getTraditionalHourName($hour) {
    $hourNames = [
        '子时', '丑时', '寅时', '卯时', '辰时', '巳时',
        '午时', '未时', '申时', '酉时', '戌时', '亥时'
    ];

    // 子时从23:00开始
    if ($hour == 23 || $hour == 0) {
        return $hourNames[0]; // 子时
    } elseif ($hour == 1 || $hour == 2) {
        return $hourNames[1]; // 丑时
    } elseif ($hour >= 3 && $hour <= 4) {
        return $hourNames[2]; // 寅时
    } elseif ($hour >= 5 && $hour <= 6) {
        return $hourNames[3]; // 卯时
    } elseif ($hour >= 7 && $hour <= 8) {
        return $hourNames[4]; // 辰时
    } elseif ($hour >= 9 && $hour <= 10) {
        return $hourNames[5]; // 巳时
    } elseif ($hour >= 11 && $hour <= 12) {
        return $hourNames[6]; // 午时
    } elseif ($hour >= 13 && $hour <= 14) {
        return $hourNames[7]; // 未时
    } elseif ($hour >= 15 && $hour <= 16) {
        return $hourNames[8]; // 申时
    } elseif ($hour >= 17 && $hour <= 18) {
        return $hourNames[9]; // 酉时
    } elseif ($hour >= 19 && $hour <= 20) {
        return $hourNames[10]; // 戌时
    } elseif ($hour >= 21 && $hour <= 22) {
        return $hourNames[11]; // 亥时
    }

    return '';
}
